package com.base.myproject.client.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.JDBCModelData;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.SendServlet;
import com.base.myproject.client.tools.XML;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.form.Radio;
import com.extjs.gxt.ui.client.widget.form.RadioGroup;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

/**
 * 负责从服务器上拷贝数据的列，将关键信息发送到服务器
 * 服务器整理数据返回xml，就如同从服务器上拷贝了数据一样。
 * 此类通常用于同单据的拷贝或者上下游单据的拷贝，也可以用于
 * 对于一个数据插入在相同界面里面的操作。
 * @author zgw
 *2009-6-21 下午05:57:17
 * javazgw@gmail.com
 */
public class BaseCopyUI {
	//需要赋值的store链表
	 java.util.LinkedList<BaseStore> basestorell = null;
	 String servletparam = null;
	 String busicopyid = null;
	 BaseGrid grid=null;
	 ContentPanel panelcenter = new ContentPanel();
	 final Dialog  dialog =new Dialog();
	  RadioGroup myRg =null;
	 String returncolumnname;
	 
	public BaseCopyUI(java.util.LinkedList<BaseStore> basestorell,String servletparam,String busicopyid)
	{
		this.basestorell = basestorell;
		this.servletparam = servletparam;
		this.busicopyid = busicopyid;
	}
	
	public Dialog initUI() throws RequestException
	{
		
		    dialog.setTopComponent(getRadioGroup());
		    dialog.add(panelcenter);
		    dialog.setButtons(Dialog.OKCANCEL);
		   dialog.getButtonById(Dialog.OK).addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				String[] strarr = returncolumnname.split(",");
				String param = "";
				for(String str:strarr)
				{
					
					System.out.println(str +"--"+grid.getValue(str));
					param +=grid.getValue(str)+",";
				}
				sendServlet(busicopyid,myRg.getValue().getBoxLabel(),param); 
			}
			   
		   });
		    dialog.show();
		   
		return dialog;
		/*
		
		
		ContentPanel panel = new ContentPanel();
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("busicopyid");
		type.addField("busicopyname");

		StoreInfo info = new StoreInfo();
		info.setTablename("busicopy");
		info.setSql("select busicopyid,busicopyname from busicopy");
		final RadioGroup myRg = new RadioGroup(){
		
			
			 protected void onRadioSelected(Radio radio) {
				 super.onRadioSelected(radio);
				 System.out.println("onradioselected");
				 System.out.println("ss"
							+ this.getValue()
									.getValue());
					System.out.println("ss"
							+ this.getValue()
									.getBoxLabel());
					
					List<ColumnConfig> customercolumns = new ArrayList<ColumnConfig>();

					ColumnConfig leaguertype = new ColumnConfig(
							"leaguertype", "家庭成员", 100);
					TextField<String> leaguertext = new TextField<String>();
					
					customercolumns.add(leaguertype);
					ColumnConfig leaguername = new ColumnConfig(
							"leaguername", "姓名", 100);
					TextField<String> leaguernametext = new TextField<String>();
					
					customercolumns.add(leaguername);

					ColumnModel customercm = new ColumnModel(
							customercolumns);

					ModelType customertype = new ModelType();
					customertype.setRoot("records");
					customertype
							.setRecordName("record");

					customertype.addField("ccode",
							"ccode");
					customertype
							.addField("leaguertype");
					customertype
							.addField("leaguertype");

					StoreInfo customerinfo = new StoreInfo();

					customerinfo
							.setTablename("ccodelinkman_info");
					customerinfo
							.setSql("select * from ccodelinkman_info");
				
					customerinfo
							.setLinkparentcolumns(new String[] { "ccode" });
					BaseStore customertypestore = new BaseStore<JDBCModelData>(
							customertype, customerinfo);
					customertypestore
							.setName("ccodelinkman_info");
					customertypestore
							.setKeyname(new String[] { "ccode" });
					 grid = new BaseGrid(
							customertypestore,
							customercm);
					 
					panelcenter.removeAll();
					panelcenter.setHeight("100px");
					panelcenter.setWidth("100%");
					panelcenter.add(grid);
					//dialog.add(panelcenter);
					//grid.setHeight(100);
					panelcenter.layout();
					dialog.layout();
					panelcenter.layout();
			 }
		};

		 Radio[] bananas = new Radio[2];
		 
		 
		  //new BaseGrid(customertypestore, customercm);
		for(int i=0;i<2;i++)
		{	
//			String busicopyid = basestore.getValue(i, "busicopyid")+"";
//			String busicopyname = basestore.getValue(i, "busicopyname")+"";
			 bananas[i] =new Radio();
			bananas[i].setBoxLabel(i+"");
			
	
			myRg.add(bananas[i]);
			
			
		}
		
	
		final BaseStore<BaseModelData> basestore = new BaseStore<BaseModelData>(type,
				info);
		
		basestore.addBaseStoreListener(BaseStoreEvent.EventType.LOAD_COMPLETE,new BaseStoreListener(){

			@Override
			public void BaseStoreEventHandle(BaseStoreEvent evt) {
				// TODO Auto-generated method stub
				
				dialog.add(myRg);
				panelcenter.setHeight("200px");
				dialog.add(panelcenter);
				List<ColumnConfig> customercolumns = new ArrayList<ColumnConfig>();

				ColumnConfig leaguertype = new ColumnConfig(
						"leaguertype", "家庭成员", 100);
				TextField<String> leaguertext = new TextField<String>();
				
				customercolumns.add(leaguertype);
				ColumnConfig leaguername = new ColumnConfig(
						"leaguername", "姓名", 100);
				TextField<String> leaguernametext = new TextField<String>();
				
				customercolumns.add(leaguername);

				ColumnModel customercm = new ColumnModel(
						customercolumns);

				ModelType customertype = new ModelType();
				customertype.setRoot("records");
				customertype
						.setRecordName("record");

				customertype.addField("ccode",
						"ccode");
				customertype
						.addField("leaguertype");
				customertype
						.addField("leaguertype");

				StoreInfo customerinfo = new StoreInfo();

				customerinfo
						.setTablename("ccodelinkman_info");
				customerinfo
						.setSql("select * from ccodelinkman_info");
			
				customerinfo
						.setLinkparentcolumns(new String[] { "ccode" });
				BaseStore customertypestore = new BaseStore<JDBCModelData>(
						customertype, customerinfo);
				customertypestore
						.setName("ccodelinkman_info");
				customertypestore
						.setKeyname(new String[] { "ccode" });
				 grid = new BaseGrid(
						customertypestore,
						customercm);
				System.out.println(grid.getStore().getCount()+"--");
				
				//dialog.setBottomComponent(grid);
			
				dialog.show();
			}

			@Override
			public void onBrowserEvent(Event event) {
				// TODO Auto-generated method stub
				
			}
			
			
		});
		

	
		    
		return null;
	*/}
	private RadioGroup getRadioGroup() {
		 myRg = new RadioGroup() {

			protected void onRadioSelected(Radio radio) {
				super.onRadioSelected(radio);
				ModelType type = new ModelType();
				type.setRoot("records");
				type.setRecordName("record");
				
				List<ColumnConfig> customercolumns = new ArrayList<ColumnConfig>();

				StoreInfo info = new StoreInfo();
				
				
				
				SendServlet ss = new SendServlet();
				String datawinstr = ss.getStringx("/"+GWT.getModuleName()+"/BaseServlet", "Action=getdatawin&busicopyname="+this.getValue().getBoxLabel()+"&busicopyid="+busicopyid);
//				System.out.println("---datawinstr="+datawinstr);
				Document doc = XMLParser.parse((String) datawinstr);

				    NodeList list = doc.getElementsByTagName("datawin");
				    for (int i = 0; i < list.getLength(); i++) {
					      Node node = list.item(i);
					      Element elem = (Element) node;
					      if(i==0)
					      {
					    	  returncolumnname =elem.getAttribute("returncolumnname");
					      }
					      NodeList columnconfiglist  = elem.getElementsByTagName("columnconfig");
					      for(int j = 0;j<columnconfiglist.getLength();j++)
					      {
					    	  Node columnconfiglistnode = columnconfiglist.item(j);
						      Element columnconfiglistelem = (Element) columnconfiglistnode;
						     
						      String width = columnconfiglistelem.getAttribute("width");
						      ColumnConfig cc =  new ColumnConfig();
						      cc.setId(columnconfiglistelem.getAttribute("id"));
						      cc.setHeader(columnconfiglistelem.getAttribute("name"));
						      cc.setWidth(width==null?100:Integer.parseInt(width));
						      customercolumns.add(cc);
					      }
					      NodeList modeltypelist  = elem.getElementsByTagName("modeltype");
					      for(int j = 0;j<modeltypelist.getLength();j++)
					      {
					    	  Node modeltypenode = modeltypelist.item(j);
						      Element modeltypeelem = (Element) modeltypenode;
						      String name = modeltypeelem.getAttribute("name");
						      String map = modeltypeelem.getAttribute("map");
						      type.addField(name,map==null?name:map);
						    
						     
					      }
					      NodeList storeinfolist  = elem.getElementsByTagName("storeinfo");
					      for(int j = 0;j<storeinfolist.getLength();j++)
					      {
					    	  Node storeinfonode = storeinfolist.item(j);
						      Element storeinfoelem = (Element) storeinfonode;
						      String name = storeinfoelem.getAttribute("name");
						      String tablename = storeinfoelem.getAttribute("tablename");
						      String sql = storeinfoelem.getAttribute("sql");
						      info.setTablename(tablename);
						      info.setSql(sql);
					      }
				    }
				    type.setTotalName("totle");
				     BaseStore<BaseModelData> basestore = new BaseStore<BaseModelData>(type,
							info);
				  	CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
				 	customercolumns.add(0, cbs.getColumn());
				 	ColumnModel cm = new ColumnModel(
							customercolumns);
				 	cbs.setSelectionMode(SelectionMode.SINGLE);
				     grid = new BaseGrid(
				    		basestore,
							cm);
				     grid.setSelectionModel(cbs);
				     grid.setLoadMask(true);
				    grid.setAutoHeight(true);
				    grid.setAutoWidth(true);
				    panelcenter.removeAll();
				    panelcenter.add(grid);
				    panelcenter.layout();
			}
		};
		String sql  = "select busicopyname from busicopy where busicopyid='"+busicopyid+"'";
		SendServlet ss = new SendServlet();
		String datawinstr = ss.getStringx("/"+GWT.getModuleName()+"/BaseServlet", "Action=getdatasql&sql="+sql+"");
		  Document doc = XMLParser.parse((String) datawinstr);
	
		    NodeList list = doc.getElementsByTagName("record");
			 Radio[] radio = new Radio[list.getLength()];
		    for (int i = 0; i < list.getLength(); i++) {
			      Node node = list.item(i);
			      Element elem = (Element) node;
			      for(int j=0; j<elem.getChildNodes().getLength();j++)
				     {
				    	 
				    	 String name =  elem.getChildNodes().item(j).getNodeName();
				    	 String value = XML.getValue(elem,name);
				    	 radio[i] = new Radio();
					      radio[i].setBoxLabel(value);
					      myRg.add( radio[i]);
				     }
			      
			      
//			      String name = node.getNodeName();
//			     
//			      String value = XML.getValue( doc.getDocumentElement(),name);
//			      radio[i] = new Radio();
//			      radio[i].setBoxLabel(value);
//			      myRg.add( radio[i]);
		    }
		    
	
		return myRg;
	}
	/**
	 * 需要赋值store 的链表
	 * @return
	 */
	public java.util.LinkedList<BaseStore> getBasestorell() {
		return basestorell;
	}

	public void setBasestorell(java.util.LinkedList<BaseStore> basestorell) {
		this.basestorell = basestorell;
	}
/**
 * 传输到服务器端的参数
 * @return
 */
	public String getServletparam() {
		return servletparam;
	}

	public void setServletparam(String servletparam) {
		this.servletparam = servletparam;
	}
/**
 * 获得拷贝id
 * @return
 */
	public String getBusicopyid() {
		return busicopyid;
	}
	public void setBusicopyid(String busicopyid) {
		this.busicopyid = busicopyid;
	}
	/**
	 *  busicopyid和busicopyname指定了表busicopy 的一行记录
	 * @param busicopyid 对应数据库表busicopy 同名字段
	 * @param busicopyname  对应数据库表busicopy同名字段
	 * @param param 用 逗号 分割的字符串
	 */
	public void sendServlet(String busicopyid,String busicopyname, String param)
	{
		SendServlet sendservlet = new SendServlet();
		try {
			sendservlet.sendServlet("gwtbase/BaseServlet", "Action=test&param="+param+"&busicopyid="+busicopyid+"&busicopyname="+busicopyname, new RequestCallback(){

				@Override
				public void onError(Request request, Throwable exception) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onResponseReceived(Request request,
						Response response) {
					// TODO Auto-generated method stub
					//System.out.println(response.getText());
				//	formpanel.getBasestore().setValue(1, "postcode", response.getText());
					  Document doc = XMLParser.parse(response.getText());
					  NodeList listroot =  doc.getElementsByTagName("basestore");
					  for(int i=0;i<listroot.getLength();i++)
					  {
						  Node node = listroot.item(i);
						  BaseStore basesotre=null;
						  String type = "1";
						  for(BaseStore bs:basestorell)
						  {
							  Element elem = (Element) node;
							  
							  System.out.println(elem.getAttribute("name"));
							  if(bs.getName().equals(elem.getAttribute("name")))
							  {
								  basesotre= bs;
								  type = elem.getAttribute("type");
								
								  break;
							  }
						  }
						  if(basesotre==null)
						  {
							  continue;
						  }
						  NodeList recordroot  = node.getChildNodes();
						//record
						  for(int j=0;j<recordroot.getLength();j++)
						  {
							  Node itemnode = recordroot.item(j);
						      Element elem = (Element) itemnode;
						      if(type.equals("1")) //插入模式，增加一条记录
					    	  {
						    	  HashMap hm = new HashMap();
					    	       JDBCModelData jdbcml = new JDBCModelData(hm);
				    	    	   basesotre.add(jdbcml);
					    		  
					    	  }
						      else if(type.equals("2"))
						      {
						    	 
						    	  //行不够，自动增加一行
						    	  GWT.log("拷贝 行记录数"+basesotre.getCount()+" 当前顺序号="+j,null);
							      if(basesotre.getCount()<=j)
							      {
							    	  basesotre.add();
							      }
							      else
							      {
							    	  basesotre.gotorow(j);
							      }
						    	 
						      }
						     
						      for(int k=0;k<elem.getChildNodes().getLength();k++)
						      {
						    	
						    	 
						    	  String name =  elem.getChildNodes().item(k).getNodeName();
						    	  basesotre.setValue( name, XML.getValue(elem,name));
						    	 
						    		  
						    
						      }
						  }
						  
					  }
	
				}
				
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
